package com.gujiangbo.config;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author: gujiangbo.co
 * @Contact: 646832012@qq.com
 * @Date: 2021/12/10 14:09
 * @Version: 1.0
 * @Description:
 */
@Component
@Scope("singleton")
public class ThreadPoolsObject {

    private static Log debugLog = LogFactory.getLog(ThreadPoolsObject.class);

    @Value("${thread.max_pool_size}")
    private int maxPoolSize;
    @Value("${thread.core_pool_size}")
    private int corePoolSize;

    @Value("${thread.keep_alive_seconds}")
    private int keepAliveSeconds;
    @Value("${thread.queue_capacity}")
    private int queueCapacity;

    @Bean("asyncThreadPoolTaskExecutor")
    public AsyncTaskExecutor asyncTaskExecutor() {
        debugLog.info("init asyncTaskExecutor......");
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setThreadNamePrefix("async-executor-");
        taskExecutor.setMaxPoolSize(maxPoolSize);
        taskExecutor.setCorePoolSize(corePoolSize);
        taskExecutor.setKeepAliveSeconds(keepAliveSeconds);
        taskExecutor.setQueueCapacity(queueCapacity);
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        return taskExecutor;
    }

    @Bean("connectThreadPoolExecutor")
    public ThreadPoolTaskExecutor connectExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setThreadNamePrefix("connect-thread-pool-executor-");
        executor.setMaxPoolSize(maxPoolSize);
        executor.setCorePoolSize(corePoolSize);
        executor.setKeepAliveSeconds(keepAliveSeconds);
        executor.setQueueCapacity(queueCapacity);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }


}


